// 大数据第七题
// author: lbc
package homework1;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;

public class mkdir_rm {
    public static void main(String[] args) throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        String hdfsPath = "hdfs://localhost:9000";
        FileSystem hdfs = FileSystem.get(new URI(hdfsPath), conf);
        String dirPath = "hdfstest";
        boolean force = false;
        if (!fileExist(hdfs, dirPath)) {
            makedir(hdfs, dirPath);
            System.out.println("make dir: " + dirPath);
        } else {
            if (force || isEmptyDir(hdfs, dirPath)) {
                remove(hdfs, dirPath);
                System.out.println("remove dir: " + dirPath);
            } else {
                System.out.println("Dir already exist! Do Nothing!");
            }
        }
        hdfs.close();
    }

    public static boolean removeDir(FileSystem fs, String dirPath) throws IOException {
        return fs.delete(new Path(dirPath), true);
    }

    public static boolean isEmptyDir(FileSystem fs, String dirPath) throws IOException {
        RemoteIterator<LocatedFileStatus> filelist = fs.listFiles(new Path(dirPath), true);
        return !filelist.hasNext();
    }

    public static boolean makedir(FileSystem fs, String dirPath) throws IOException {
        boolean res = fs.mkdirs(new Path(dirPath));
        return res;
    }

    public static boolean remove(FileSystem fs, String file_path) throws IOException {
        boolean res = fs.delete(new Path(file_path), false);
        return res;
    }

    public static void touchfile(FileSystem fs, String file_path) throws IOException {
        FSDataOutputStream out = fs.create(new Path(file_path));
        out.close();
    }

    public static boolean fileExist(FileSystem fs, String file_path) throws IOException {
        return fs.exists(new Path(file_path));
    }

}
